package com.pmdb.core.data;

import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.apache.log4j.Logger;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

@Entity
@Table(name = "T_COUNTRY")
public class Country implements Comparable<Country>{
   
   private static final Logger LOG = Logger.getLogger(Country.class);

   @Id @GeneratedValue
   @Column(name = "ID")
   private Long id;

   @Column(name = "NAME", nullable=false, unique=true)
   private String name;

   @ManyToMany(
         mappedBy = "countries"
   )
   @Sort(type = SortType.NATURAL)
   private SortedSet<Movie> movies;

   public Country() {
      this.movies = new TreeSet<Movie>();
   }

   public Country(String name) {
      this();
      this.name = name;
   }

   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public SortedSet<Movie> getMovies() {
      return Collections.unmodifiableSortedSet(this.movies);
   }

   public void addMovie(Movie movie) {
      this.addMovie(movie, true);
   }

   public void addMovie(Movie movie, boolean linkBack) {
      if(movie == null) {
         throw new IllegalArgumentException("Null movie!");
      }
      this.movies.add(movie);
      LOG.debug("New movie for this country: " + name);
      if(linkBack) {
         movie.addCountry(this, false);
      }
   }
   
   public void removeMovie(Movie movie) {
      this.removeMovie(movie, true);
   }
   
   public void removeMovie(Movie movie, boolean removeLinkBack) {
      if(movie == null) {
         throw new IllegalArgumentException("Null movie!");
      }
      this.movies.remove(movie);
      if(removeLinkBack) {
         movie.removeCountry(this, false);
      }
   }
   
   @Override
   public String toString() {
      StringBuilder strBld = new StringBuilder();
      strBld.append("Country={[");
      strBld.append(id);
      strBld.append("] ");
      strBld.append(name);
      strBld.append("}");
      
      return strBld.toString();
   }
   
   @Override
   public int compareTo(Country comp) {
      return this.name.compareTo(comp.name);
   }
}
